"""
调用存储服务：
自定义存储类
"""

from fdfs_client.client import Fdfs_client
from django.core.files.storage import Storage
from django.conf import settings
from django.utils.deconstruct import deconstructible


@deconstructible
class FastDFSStorage(Storage):
    """
    自定义存储类
    读取上传的文件，保存文件到FastDFS中，访问url， 是否存在 ，文件重名问题
    """

    # def __init__(self, base_url=None, client_url=None):
    #     self.base_url = settings.FDFS_URL
    #     self.client_url = settings.DEFAULT_FILE_STORAGE

    def _open(self, name, mode='rb'):
        pass

    def _save(self, name, content):
        # client = Fdfs_client(self.client_url)
        client = Fdfs_client('/home/pyvip/hk27/haoke_mall/haoke_mall/utils/fastdfs/client.conf')

        ret = client.upload_by_buffer(content.read())
        #  判断是否上传成功
        if ret.get('Status') != 'Upload successed.':
            raise Exception('Upload file failed')

        file_name = ret.get('Remote file_id')
        return file_name

    def url(self, name):
        """
        返回文件的url  上传文件后的路径
        """
        return settings.FDFS_URL + name

    def exists(self, name):
        return None
